from django.utils.decorators import method_decorator
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django.conf import settings
from apps.ai.services.voice_service import VoiceService, VoiceServiceError, RateLimitExceededError
import logging
from django.views.decorators.csrf import csrf_exempt
from rest_framework.permissions import IsAuthenticated

logger = logging.getLogger('apps')

@method_decorator(csrf_exempt, name='dispatch')
class VoiceRecognitionView(APIView):
    """语音识别视图"""
    permission_classes = [IsAuthenticated]
    
    def post(self, request):
        try:
            # 获取音频文件
            voice_file = request.FILES.get('voice')
            if not voice_file:
                return Response({
                    'status': 'error',
                    'message': '未接收到音频文件'
                }, status=status.HTTP_400_BAD_REQUEST)
            
            # 记录音频信息
            user_id = request.user.pk if request.user.is_authenticated else 'anonymous'
            logger.info(
                "接收到音频文件: 用户=%s, 文件名=%s, 大小=%d字节",
                user_id,
                voice_file.name,
                voice_file.size
            )
            
            # 初始化语音服务
            api_key = settings.BAIDU_SPEECH_API_KEY
            secret_key = settings.BAIDU_SPEECH_SECRET_KEY
            voice_service = VoiceService(api_key, secret_key)
            
            # 验证音频
            validation = voice_service.validate_audio(voice_file)
            if not validation.is_valid:
                logger.warning("无效音频文件，用户=%s，文件名=%s，大小=%s", 
                             user_id, voice_file.name, voice_file.size)
                return Response({
                    'status': 'error',
                    'message': validation.message or '请上传有效的音频文件'
                }, status=status.HTTP_400_BAD_REQUEST)
            
            # 执行语音识别
            recognized_text = voice_service.recognize_audio(voice_file)
            
            return Response({
                'status': 'success',
                'data': {
                    'text': recognized_text
                }
            })
            
        except RateLimitExceededError as e:
            logger.warning("语音识别频率限制: %s", str(e))
            return Response({
                'status': 'error',
                'message': str(e),
                'code': 'RATE_LIMIT_ERROR'
            }, status=status.HTTP_429_TOO_MANY_REQUESTS)
            
        except VoiceServiceError as e:
            logger.error(
                "语音识别服务错误: 错误=%s, 代码=%s",
                str(e),
                e.code
            )
            
            return Response({
                'status': 'error',
                'message': str(e),
                'code': e.code
            }, status=e.http_status)
            
        except Exception as e:
            logger.error(
                "语音识别失败: 错误=%s",
                str(e),
                exc_info=True
            )
            
            return Response({
                'status': 'error',
                'message': f'语音识别失败: {str(e)}',
                'code': 'RECOGNITION_ERROR'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)